// 获取今天的日期
const today = new Date();
const currentYear = today.getFullYear();
const currentMonth = today.getMonth() + 1;
const currentDay = today.getDate();
let selectedDay = null; // 添加全局selectedDay变量

function updateWeekday() {
    const year = yearSelect.value;
    const month = monthSelect.value.padStart(2, '0');
    const day = selectedDay ? selectedDay.textContent.padStart(2, '0') : currentDay.toString().padStart(2, '0');
    const date = new Date(`${year}-${month}-${day}`);
    const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    const weekdayElement = document.getElementById('weekday');
    const dayOfWeek = date.getDay();
    weekdayElement.textContent = weekdays[dayOfWeek];
    weekdayElement.style.fontWeight = 'bold';
    weekdayElement.style.color = dayOfWeek === 0 || dayOfWeek === 6 ? '#FF5722' : '#000';
}

// 初始化年份选择器（2024-2030年）
const yearSelect = document.getElementById('yearSelect');
for(let year = 2024; year <= 2030; year++) {
    const option = document.createElement('option');
    option.value = year;
    option.text = year + '年';
    if (year === currentYear) {
        option.selected = true;
    }
    yearSelect.appendChild(option);
}

// 初始化月份选择器
const monthSelect = document.getElementById('monthSelect');
for(let month = 1; month <= 12; month++) {
    const option = document.createElement('option');
    option.value = month;
    option.text = month + '月';
    if (month === currentMonth) {
        option.selected = true;
    }
    monthSelect.appendChild(option);
}

// 加载状态控制
function showLoading() {
    const loadingOverlay = document.querySelector('.loading-overlay');
    loadingOverlay.classList.add('active');
}

function hideLoading() {
    const loadingOverlay = document.querySelector('.loading-overlay');
    loadingOverlay.classList.remove('active');
}

// 页面加载完成后隐藏加载状态
window.addEventListener('load', () => {
    hideLoading();
});

// 修改updateCalendar函数，添加加载状态
function updateCalendar() {
    showLoading();
    
    const year = parseInt(yearSelect.value);
    const month = parseInt(monthSelect.value);
    const firstDay = new Date(year, month - 1, 1);
    const lastDay = new Date(year, month, 0);
    const daysInMonth = lastDay.getDate();
    const firstDayOfWeek = firstDay.getDay();
    
    const calendarGrid = document.getElementById('calendarGrid');
    calendarGrid.innerHTML = '';
    
    // 添加星期标题
    const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
    weekdays.forEach(day => {
        const weekdayElement = document.createElement('div');
        weekdayElement.className = 'calendar-weekday';
        weekdayElement.textContent = day;
        calendarGrid.appendChild(weekdayElement);
    });
    
    // 添加上个月的日期
    const prevMonthDays = new Date(year, month - 1, 0).getDate();
    for (let i = firstDayOfWeek - 1; i >= 0; i--) {
        const dayElement = document.createElement('div');
        dayElement.className = 'calendar-day other-month';
        dayElement.textContent = prevMonthDays - i;
        calendarGrid.appendChild(dayElement);
    }
    
    // 添加当前月的日期
    for (let day = 1; day <= daysInMonth; day++) {
        const dayElement = document.createElement('div');
        dayElement.className = 'calendar-day';
        const date = new Date(year, month - 1, day);
        const isWeekend = date.getDay() === 0 || date.getDay() === 6;
        
        if (isWeekend) {
            dayElement.classList.add('weekend');
        }
        if (year === currentYear && month === currentMonth && day === currentDay) {
            dayElement.classList.add('today');
        }
        
        dayElement.textContent = day;
        dayElement.onclick = () => selectDate(day);
        calendarGrid.appendChild(dayElement);
    }
    
    // 添加下个月的日期
    const remainingDays = 42 - (firstDayOfWeek + daysInMonth);
    for (let day = 1; day <= remainingDays; day++) {
        const dayElement = document.createElement('div');
        dayElement.className = 'calendar-day other-month';
        dayElement.textContent = day;
        calendarGrid.appendChild(dayElement);
    }
    
    updateWeekday();
    
    // 延迟隐藏加载状态，确保动画完成
    setTimeout(hideLoading, 300);
}

function selectDate(day) {
    const prevSelectedDay = document.querySelector('.calendar-day.selected');
    if (prevSelectedDay) {
        prevSelectedDay.classList.remove('selected');
    }
    
    const dayElements = document.querySelectorAll('.calendar-day:not(.other-month)');
    dayElements.forEach(element => {
        if (parseInt(element.textContent) === day) {
            element.classList.add('selected');
            selectedDay = element; // 更新全局selectedDay变量
            updateWeekday(); // 更新星期显示
            // 触发点击事件
            element.click();
            checkWorkDay(); // 自动执行查询
        }
    });
}

// 监听年月变化，更新日历
yearSelect.addEventListener('change', updateCalendar);
monthSelect.addEventListener('change', updateCalendar);

// 添加月份导航按钮事件
document.getElementById('prevMonth').addEventListener('click', () => {
    let month = parseInt(monthSelect.value);
    let year = parseInt(yearSelect.value);
    if (month === 1) {
        month = 12;
        year--;
    } else {
        month--;
    }
    yearSelect.value = year;
    monthSelect.value = month;
    updateCalendar();
});

document.getElementById('nextMonth').addEventListener('click', () => {
    let month = parseInt(monthSelect.value);
    let year = parseInt(yearSelect.value);
    if (month === 12) {
        month = 1;
        year++;
    } else {
        month++;
    }
    yearSelect.value = year;
    monthSelect.value = month;
    updateCalendar();
});

// 初始化日历
updateCalendar();

// 自动选中当前日期
selectDate(currentDay);

// 自动执行查询
checkWorkDay();

function getRandomDrinkAmount(type) {
    switch(type) {
        case '白酒':
            // 生成0.1-2斤的随机数，保留一位小数
            return `${(Math.random() * 1.9 + 0.1).toFixed(1)}斤`;
        case '啤酒':
            return `${Math.floor(Math.random() * 20) + 1}瓶`;
        case '红酒':
            return Math.random() < 0.5 ? '半瓶' : '一瓶';
        default:
            return '';
    }
}

// 修改checkWorkDay函数，添加加载状态
function checkWorkDay() {
    showLoading();
    
    const year = yearSelect.value;
    const month = monthSelect.value.padStart(2, '0');
    const selectedDay = document.querySelector('.calendar-day.selected');
    if (!selectedDay) return;
    const day = selectedDay.textContent.padStart(2, '0');
    const selectedDate = new Date(`${year}-${month}-${day}`);
    const startDate = new Date('2025-03-02');
    
    const diffTime = Math.abs(selectedDate - startDate);
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
    
    const remainder = diffDays % 4;  // 4天周期
    const isWorkDay = remainder === 0 || remainder === 1;  // 前2天上班，后2天休息
    
    const resultElement = document.getElementById('result');
    const dateString = selectedDate.toLocaleDateString('zh-CN');
    
    // 延迟显示结果，配合动画效果
    setTimeout(() => {
        if (isWorkDay) {
            resultElement.style.color = '#4CAF50';
            resultElement.textContent = `${dateString} 今天上班不能喝酒`;
        } else {
            resultElement.style.color = '#FF5722';
            const drinks = ['白酒', '啤酒', '红酒'];
            const count = Math.floor(Math.random() * 3) + 1; // 随机选择1-3种酒
            const shuffled = drinks.sort(() => 0.5 - Math.random());
            const selected = shuffled.slice(0, count);
            const drinksWithAmount = selected.map(drink => `${drink}${getRandomDrinkAmount(drink)}`);
            resultElement.textContent = `${dateString} 今天休息，适合喝${drinksWithAmount.join('、')}`;
        }
        hideLoading();
    }, 300);
}

// 主题切换功能
document.addEventListener('DOMContentLoaded', function() {
    const themeToggle = document.getElementById('themeToggle');
    const themeColorBtns = document.querySelectorAll('.theme-color-btn');
    const themeControls = document.querySelector('.theme-controls');
    let hideTimeout;
    
    // 从localStorage加载主题设置
    const savedTheme = localStorage.getItem('theme');
    const savedThemeColor = localStorage.getItem('themeColor');
    
    if (savedTheme) {
        document.documentElement.setAttribute('data-theme', savedTheme);
        updateThemeIcon(savedTheme);
    }
    
    if (savedThemeColor) {
        document.documentElement.setAttribute('data-theme-color', savedThemeColor);
    }
    
    // 自动隐藏控制面板
    function startHideTimer() {
        clearTimeout(hideTimeout);
        hideTimeout = setTimeout(() => {
            themeControls.classList.add('hidden');
        }, 3000);
    }
    
    // 显示控制面板
    function showControls() {
        themeControls.classList.remove('hidden');
        startHideTimer();
    }
    
    // 鼠标进入控制面板时取消隐藏
    themeControls.addEventListener('mouseenter', () => {
        clearTimeout(hideTimeout);
    });
    
    // 鼠标离开控制面板时开始隐藏计时
    themeControls.addEventListener('mouseleave', startHideTimer);
    
    // 点击显示/隐藏触发器
    themeControls.addEventListener('click', (e) => {
        if (e.target === themeControls || e.target === themeControls.querySelector('::before')) {
            showControls();
        }
    });
    
    // 深色模式切换
    themeToggle.addEventListener('click', function() {
        const currentTheme = document.documentElement.getAttribute('data-theme');
        const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
        
        document.documentElement.setAttribute('data-theme', newTheme);
        localStorage.setItem('theme', newTheme);
        updateThemeIcon(newTheme);
        startHideTimer();
    });
    
    // 主题色切换
    themeColorBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const themeColor = this.getAttribute('data-theme');
            document.documentElement.setAttribute('data-theme-color', themeColor);
            localStorage.setItem('themeColor', themeColor);
            startHideTimer();
        });
    });
    
    // 更新主题图标
    function updateThemeIcon(theme) {
        const icon = themeToggle.querySelector('.theme-icon');
        icon.textContent = theme === 'dark' ? '☀️' : '🌙';
    }
    
    // 检测系统主题偏好
    if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
        if (!savedTheme) {
            document.documentElement.setAttribute('data-theme', 'dark');
            localStorage.setItem('theme', 'dark');
            updateThemeIcon('dark');
        }
    }
    
    // 监听系统主题变化
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
        if (!savedTheme) {
            const newTheme = e.matches ? 'dark' : 'light';
            document.documentElement.setAttribute('data-theme', newTheme);
            localStorage.setItem('theme', newTheme);
            updateThemeIcon(newTheme);
        }
    });
    
    // 初始化时显示控制面板
    showControls();
});

// 添加触摸反馈效果
document.addEventListener('DOMContentLoaded', function() {
    const buttons = document.querySelectorAll('.ripple');
    
    buttons.forEach(button => {
        button.addEventListener('click', function(e) {
            const rect = button.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;
            
            const ripple = document.createElement('span');
            ripple.style.left = `${x}px`;
            ripple.style.top = `${y}px`;
            
            button.appendChild(ripple);
            
            setTimeout(() => {
                ripple.remove();
            }, 600);
        });
    });
});